package com.xixisleep.apigateway;

import com.xixisleep.apicommon.model.entity.InterfaceInfo;
import com.xixisleep.apicommon.model.entity.User;
import com.xixisleep.apicommon.service.InnerInterfaceInfoService;
import com.xixisleep.apicommon.service.InnerUserInterfaceInfoService;
import com.xixisleep.apicommon.service.InnerUserService;
import com.xixisleep.yeapiclientsdk.utils.SignUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * 全局过滤
 */
@Component
@Slf4j
public class CustomGlobalFilter implements GlobalFilter, Ordered{
    @DubboReference
    private InnerUserService innerUserService;

    @DubboReference
    private InnerInterfaceInfoService interfaceInfoService;

    @DubboReference
    private InnerUserInterfaceInfoService innerUserInterfaceInfoService;

    private static final List<String> IP_WHITE_LIST = Arrays.asList("127.0.0.1");

    private static final String INTERFACE_HOST = "http://localhost:6679";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 请求日志
        ServerHttpRequest request = exchange.getRequest();
        String realUrl = INTERFACE_HOST + request.getPath().value();
        String method = request.getMethod().toString();
        log.info("请求唯一标识："+request.getId());
        log.info("请求路径："+ request.getPath().value());
        log.info("请求方法"+ method);
        log.info("请求参数"+request.getQueryParams());
        String sourceAddress = request.getLocalAddress().getHostString();
        log.info("请求来源地址"+sourceAddress);

        //2.（黑白名单）
        //拿到响应对象
        ServerHttpResponse response = exchange.getResponse();
        if (!IP_WHITE_LIST.contains(sourceAddress)) {
            //设置响应状态码为403，Forbidden（禁止访问）
            return handleNoAuth(response);
        }

        //3.用户鉴权（判断ak,sk是否合法）
        //从请求头中获取参数
        HttpHeaders headers = request.getHeaders();
        String accessKey = headers.getFirst("accessKey");
        String nonce = headers.getFirst("nonce");
        String body = headers.getFirst("body");
        String timestamp = headers.getFirst("timestamp");
        String sign = headers.getFirst("sign");
        //去数据库中查是否已分配给用户
        User invokeUser = null;
        try {
            //调用内部服务，根据访问密钥获取用户信息
            invokeUser = innerUserService.getInvokeUser(accessKey);
            if (invokeUser == null) {
                //如果用户信息为空，处理为授权情况并返回响应
                return handleNoAuth(response);
            }
        }catch (Exception e){
            //捕获异常
            log.error("getInvokeUser error",e);
        }

        if (!accessKey.equals(invokeUser.getAccessKey())) {
            return handleNoAuth(response);
        }
        //随机数大于5位数
        if (Long.parseLong(nonce) > 10000) {
            return handleNoAuth(response);
        }
        //时间和当前时间不能超过5分钟
        Long sendTime = Long.parseLong(timestamp);
        Long currentTime= System.currentTimeMillis() / 1000;
        if (currentTime - sendTime > 5 * 60) {
            return handleNoAuth(response);
        }
        //拼接出hashmap
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("accessKey",accessKey);
        hashMap.put("nonce", nonce);
        hashMap.put("body", body);
        hashMap.put("timestamp", timestamp);
        //过accessKey从数据库中查secretKey
        //从获取到的用户信息中获取用户的密钥
        String secretKey = invokeUser.getSecretKey();
        //使用获取到的密钥生成摘要
        String serverSign = SignUtils.generateSign(hashMap, secretKey);
        //如果生成的签名不一致，则抛出异常，并提醒“无权限”
        if (!serverSign.equals(sign)) {
            return handleNoAuth(response);
        }

        //4.请求的模拟接口是否存在？
        //todo 从数据库中查询模拟接口是否存在，以及请求方法是否匹配（还可以校验请求参数）
        InterfaceInfo interfaceInfo = null;
        try {
            //尝试从内部接口信息服务获取指定路径和方法的接口信息
            interfaceInfo = interfaceInfoService.getInterfaceInfo(realUrl,method);
            //是否成功获取接口信息
            if (interfaceInfo == null) {
                return handleNoAuth(response);
            }
        }catch (Exception e){
            log.error("getInterfaceInfo error",e);
        }

        //todo 是否还有调用次数

        //5.请求转发，调用模拟接口
        return handleResponse(exchange,chain,interfaceInfo.getId(),invokeUser.getId());

//
//        if (response.getStatusCode() == HttpStatus.OK) {
//
//        } else {
//            //8.调用失败，返回一个规范的错误码
//            return handleInvokeError(response);
//        }
//        return filter;
    }

    @Override
    public int getOrder() {
        return -1;
    }

    /**
     * 处理响应
     *
     * @param exchange
     * @param chain
     * @return
     */
    public Mono<Void> handleResponse(ServerWebExchange exchange, GatewayFilterChain chain,long interfaceId,long userId){
        try {
            //获取原始的响应对象
            ServerHttpResponse originalResponse = exchange.getResponse();
            //获取数据缓冲工厂
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            //获取响应的状态码
            HttpStatus statusCode = originalResponse.getStatusCode();

            if(statusCode == HttpStatus.OK){
                //创建一个装饰后的响应对象
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {

                    //重写writeWith方法，用户处理响应体的数据
                    //这段方法就是只要当我们的模拟接口调用完成后，等它返回结果，就会调用writhWith方法，然后根据结果做一些自己的事
                    @Override
                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                        log.info("body instanceof Flux: {}", (body instanceof Flux));
                        //判断响应体是否事Flux类型
                        if (body instanceof Flux) {
                            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                            //返回一个处理后的响应体
                            //（这里就理解为它在拼接字符串，它把缓冲区的数据取出来，一点点拼接好
                            return super.writeWith(fluxBody.map(dataBuffer -> {
                                //7.todo 调用成功，接口调用次数+1
                                try{
                                    //调用内部用户接口信息服务，记录接口嗲用次数
                                    innerUserInterfaceInfoService.invokeCount(interfaceId,userId);
                                }catch (Exception e){
                                    log.error("invokeCount error",e);
                                }
                                //读取响应体的内容并转换为字节数组
                                byte[] content = new byte[dataBuffer.readableByteCount()];
                                dataBuffer.read(content);
                                DataBufferUtils.release(dataBuffer);//释放掉内存
                                // 构建日志
                                StringBuilder sb2 = new StringBuilder(200);
                                List<Object> rspArgs = new ArrayList<>();
                                rspArgs.add(originalResponse.getStatusCode());
                                //rspArgs.add(requestUrl);
                                String data = new String(content, StandardCharsets.UTF_8);//data
                                sb2.append(data);
                                //打印日志
                                log.info("响应结果："+data);
                                log.info(sb2.toString(), rspArgs.toArray());//log.info("<-- {} {}\n", originalResponse.getStatusCode(), data);
                                return bufferFactory.wrap(content);
                            }));
                        } else {
                            log.error("<--- {} 响应code异常", getStatusCode());
                        }
                        return super.writeWith(body);
                    }
                };
                //对于200 ok的请求，将装饰后的响应对象传递给下一个过滤器链，并继续处理（设置response对象为装饰过的）
                return chain.filter(exchange.mutate().response(decoratedResponse).build());
            }
            //对于非200 ok请求，直接返回，进行降级处理
            return chain.filter(exchange);//降级处理返回数据
        }catch (Exception e){
            //处理异常情况，记录错误日志
            log.error("gateway log exception.\n" + e);
            return chain.filter(exchange);
        }
    }

    public Mono<Void> handleNoAuth(ServerHttpResponse response){
        response.setStatusCode(HttpStatus.FORBIDDEN);
        return response.setComplete();
    }

    public Mono<Void> handleInvokeError(ServerHttpResponse response){
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        return response.setComplete();
    }
}
